const path= require('path')
const WebSocket = require('ws')
const fileUtils = require('../utils/file_utils')
// 创建websocket服务对象，绑定端口是9998
const wss = new WebSocket.Server({
    port: 9998
})

module.exports.listen = () => {
    // 对客服端的连接事件进行绑定 client代表是客服端的连接socket对象
    wss.on('connection', client => {
        console.log('有客服端连接成功了。。。。')
        //  对客服端的连接对象进行message事件监听
        client.on('message', async msg => {
            let payload = JSON.parse(msg)
            if(payload.action == 'fullSreen' || payload.action == 'themeChange' ){
                console.log('接受数据的监听', payload)
                //原封不动的返回数据
                // wss.clients 所以客服端的连接
                wss.clients.forEach(allClent => {
                    allClent.send(msg)
                })
            }else {
                const payloadNew = JSON.parse(payload)
                let filePath = '../data/' + payloadNew.chartName + '.json'
                filePath = path.join(__dirname, filePath)
                  const ret =await fileUtils.getFileJsonData(filePath)
                  payloadNew.data = ret
                client.send(JSON.stringify(payloadNew))
            }
            // 有服务端往前端发送数据
            //   client.send('hello socket from backend')
        })
    })

}

